package com.example.Controller;

import com.example.Utils.RegexPatterns;
import com.example.annotation.AutoLog;
import com.example.annotation.LoginCheck;
import com.example.pojo.Common.OperationType;
import com.example.pojo.PageInfo;
import com.example.pojo.Result;
import com.example.pojo.User;
import com.example.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    @AutoLog(OperationType.POST)
    public Result<String> login(@RequestBody User user){
        log.info("用户登录:{}",user.toString());
        boolean flag = userService.login(user);
        return flag ?Result.success():Result.error("账号或密码错误");
    }
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody User user){
        log.info("用户注册：{}",user.toString());
        String phone = user.getPhone();
        if(!phone.matches(RegexPatterns.PHONE_REGEX)) return Result.error("请输入正确的电话");
        userService.insert(user);
        return Result.success();
    }

    /**
     * 用户分页查询
     */
    @GetMapping("/page")
    @LoginCheck
    public Result<PageInfo> PageQuery(int page, int PageSize){
        log.info("开始分页查询");
        return userService.pageQuery(page,PageSize);
        // return Result.success();
    }

    @GetMapping("/{id}")
    // @CachePut(cacheNames = "userCahce",key = "#id")
    public Result<User> queryById(@PathVariable int id){
        User user = userService.getById(id);
        user.setPassword("******");
        return Result.success(user);
    }


}
